//
//  GTChoicenessHeaderView.m
//  GiftTalk
//
//  Created by Wan on 16/3/23.
//  Copyright © 2016年 Wan. All rights reserved.
//

#import "GTChoicenessHeaderView.h"
#import "GTPageScrollView.h"
#import <AFNetworking.h>
#import "GTVerticalButton.h"
#import "GTPromotion.h"
#import <UIButton+WebCache.h>
#import "GTGoodThingViewController.h"
#import "GTFeaturesViewController.h"
#import "GTSignViewController.h"
#import "GTLuckyViewController.h"
#import "GTBanner.h"
#import "GTBannerTarget.h"
#import <MJExtension.h>
#import "GTWebViewController.h"
#import "GTNavigationController.h"

@interface GTChoicenessHeaderView() <GTPageScrollViewDelegate>

@property (weak, nonatomic) IBOutlet GTPageScrollView *pageScrollView;
@property (weak, nonatomic) IBOutlet UIView *buttonsSuperView;

/** 轮播图数据 */
@property (nonatomic,strong) NSArray *banners;
/** 促销按钮数据 */
@property (nonatomic,strong) NSArray *promotions;

@property (nonatomic,strong) AFHTTPSessionManager *manager;

@end

@implementation GTChoicenessHeaderView

#pragma mark 懒加载
- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (void)setBanners:(NSArray *)banners
{
    _banners = banners;
    
    [self setupPageScrollView];
}

- (void)setPromotions:(NSArray *)promotions
{
    _promotions = promotions;
    
    [self setupIconButtons];
}

#pragma mark 初始化
+ (instancetype)header
{
    // 1. 创建 tableHeaderView
    GTChoicenessHeaderView *headerView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] firstObject];
    headerView.pageScrollView.pageControlPostion = GTPageControlPositionBottomCenter;
    headerView.pageScrollView.delegate = headerView;
    
    // 2. 设置 tableHeaderView 的 frame
    headerView.frame = CGRectMake(0, 0, GTScreenW, 240);
    
    // 3. 获取焦点图 & 促销信息
    [headerView getBannersData];
    [headerView getPromotionsData];
    
    return headerView;
}

- (void)setupPageScrollView
{
    NSArray *imageURLStrings = [self.banners valueForKey:@"image_url"];
    self.pageScrollView.imageURLStrings = imageURLStrings;
    
    // 启动轮播
    [self.pageScrollView startAutoPagingWithDuration:3.0];
}

- (void)setupIconButtons
{
    [self.buttonsSuperView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat btnW = self.buttonsSuperView.width / self.promotions.count;
    CGFloat btnH = self.buttonsSuperView.height;
    
    for (NSInteger i = 0; i < self.promotions.count; i++) {
        GTVerticalButton *btn = [GTVerticalButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(btnW * i, 0, btnW, btnH);
        btn.titleLabel.font = [UIFont systemFontOfSize:12.0];
        [self.buttonsSuperView addSubview:btn];
        
        GTPromotion *promotion = self.promotions[i];
        [btn addTarget:self action:@selector(promotionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn sd_setImageWithURL:[NSURL URLWithString:promotion.icon_url] forState:UIControlStateNormal];
        [btn setTitle:promotion.title forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor colorWithHexString:promotion.color] forState:UIControlStateNormal];
    }
}

/**
 *  促销信息按钮点击事件
 */
- (void)promotionButtonClick:(GTVerticalButton *)btn
{
    NSInteger index = [self.buttonsSuperView.subviews indexOfObject:btn];
    
    GTNavigationController *navVc = [[UIApplication sharedApplication].keyWindow.rootViewController.childViewControllers firstObject];
    UIViewController *vc = nil;
    switch (index) {
        case 0:
            vc = [[GTGoodThingViewController alloc] init];
            break;
        case 1:
            vc = [[GTFeaturesViewController alloc] init];
            break;
        case 2:
            vc = [[GTSignViewController alloc] init];
            break;
        case 3:
            vc = [[GTLuckyViewController alloc] init];
            break;
        default:
            break;
    }
    
    [navVc pushViewController:vc animated:YES];
}

#pragma mark 获取数据
- (void)getBannersData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"channel"] = @"iOS";
    
    [self.manager GET:@"http://api.liwushuo.com/v1/banners" parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.banners = [GTBanner mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"banners"]];
//        GTLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        GTLog(@"%@",error);
    }];
    
}


- (void)getPromotionsData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"gender"] = @"1";
    params[@"generation"] = @"1";
    
    [self.manager GET:@"http://api.liwushuo.com/v2/promotions" parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.promotions = [GTPromotion mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"promotions"]];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        GTLog(@"%@", error);
    }];
}

- (void)dealloc
{
    [self.manager invalidateSessionCancelingTasks:YES];
}

#pragma mark - <GTPageScrollViewDelegate>
- (void)pageScrollView:(GTPageScrollView *)pageScrollView didClickImageAtIndex:(NSInteger)index
{
    GTBanner *banner = self.banners[index];
    GTNavigationController *navVc = [[UIApplication sharedApplication].keyWindow.rootViewController.childViewControllers firstObject];
    
    if ([banner.type isEqualToString:@"collection"]) {
        NSString *firstPageURLString = [NSString stringWithFormat:@"http://api.liwushuo.com/v1/%@s/%@/posts?gender=1&generation=1&limit=20&offset=0", banner.type, banner.target_id];

        GTChannelViewController *channelVc = [[GTChannelViewController alloc] init];
        channelVc.firstPageURLString = firstPageURLString;
        channelVc.title = banner.target.title;
        channelVc.dataArrayName = @"post";
        
        [navVc pushViewController:channelVc animated:YES];
    }else if ([banner.type isEqualToString:@"url"]) {
        GTWebViewController *webVc = [[GTWebViewController alloc] init];
        webVc.webURLString = banner.target_url;
        webVc.title = banner.target.title;
        
        [navVc pushViewController:webVc animated:YES];
    }else if ([banner.type isEqualToString:@"post"]) {
        GTWebViewController *webVc = [[GTWebViewController alloc] init];
        webVc.webURLString = banner.target_url;
        webVc.title = banner.target.title;
        
        [navVc pushViewController:webVc animated:YES];
    }
    
}

@end
